package com.vinjogames.network;

import org.json.JSONArray;
import org.json.JSONObject;

import com.vinjogames.entities.AttackObject;
import com.vinjogames.entities.Base;
import com.vinjogames.entities.Turret;
import com.vinjogames.entities.Unit;
import com.vinjogames.util.Logger;

public class JSONHelper {

	public static JSONObject unitToJSON(Unit u, int index){
		JSONObject jo = null;
		try {
			jo = new JSONObject();
			jo.put("Index", index);
			jo.put("Angle", u.getGun().getAngle());
			jo.put("Force", u.getCurrentForce());
			jo.put("Direction", u.getDirection());
			jo.put("Health", u.getHealth());
			jo.put("x"    , u.getLocation().x);
			jo.put("y"    , u.getLocation().y);
			jo.put("Player", u.getPlayer().isFirstPlayer());
		} catch (Exception e) {
			Logger.e(e);
		}
		return jo;
	}

	public static JSONObject baseToJSON(Base b){
		JSONObject jo = null;
		try {
			jo = new JSONObject();
			jo.put("Health", b.getHealth());
			jo.put("x"    , b.getLocation().x);
			jo.put("y"    , b.getLocation().y);
			jo.put("Player", b.getPlayer().isFirstPlayer());
		} catch (Exception e) {
			Logger.e(e);
		}
		return jo;
	}

	public static JSONObject turretToJSON(Turret t, int index){
		JSONObject jo = null;
		try {
			jo = new JSONObject();
			jo.put("Index", index);
			jo.put("Angle", t.getGun().getAngle());
			jo.put("Force", t.getCurrentForce());
			jo.put("Direction", t.getDirection());
			jo.put("Health", t.getHealth());
			jo.put("x"    , t.getLocation().x);
			jo.put("y"    , t.getLocation().y);
			jo.put("Player", t.getMyPlayer().isFirstPlayer());
		} catch (Exception e) {
			Logger.e(e);
		}
		return jo;
	}

	public static JSONArray arrayToJSON(Object[] array){
		JSONArray ja = new JSONArray();
		try{
			for(int i = 0; i < array.length; i++){
				if(array[i] instanceof Unit){
					ja.put(unitToJSON((Unit)array[i],i));
				}else if(array[i] instanceof Base){
					ja.put(baseToJSON((Base)array[i]));
				}else if(array[i] instanceof Turret){
					ja.put(turretToJSON((Turret)array[i],i));
				}
			}
		}
		catch(Exception e){
			Logger.e(e);
		}
		return ja;
	}

	public static void JSONToAttackObject(AttackObject ao, JSONObject jo){
		try {
			ao.getGun().setAngle(Float.parseFloat(jo.getString("Angle")));
			ao.setCurrentForce(Float.parseFloat(jo.getString("Force")));
			ao.getLocation().set(Float.parseFloat(jo.getString("x")),Float.parseFloat(jo.getString("y")));
			ao.setHealth(Float.parseFloat(jo.getString("Health")));
			ao.setDirection(jo.getBoolean("Direction"));
		} catch (Exception e) {
			Logger.e(e);
		} 
	}
}
